package com.iuie.ns.frame.web.dataset.context;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.iuie.ns.frame.web.dataset.annotation.DataSet;
import com.iuie.ns.frame.web.dataset.description.DataFieldDescription;
import com.iuie.ns.frame.web.dataset.description.DataSetDescription;

/**
 * 从类的注解上获取到DataSet的描述，即DataSetDescription的处理核心类
 * 
 * @author lj
 * @date 2016年12月13日15:20:29
 */
class DataSetAnnotationHandler {

	private Class<?> clazz;

	/**
	 * 构造方法
	 * 
	 * @param clazz
	 *            待处理的类
	 * @param context
	 *            上下文对象
	 */
	protected DataSetAnnotationHandler(Class<?> clazz) {
		this.clazz = clazz;
	}

	/**
	 * 处理clazz对应的类的DataSet注解，并得到DataSetDescription
	 * 
	 * @return
	 * @throws ClassNotFoundException
	 */
	protected DataSetDescription handle() throws ClassNotFoundException {
		DataSetDescription description = new DataSetDescription();
		String name = clazz.getName();
		Class<?> clazz = Class.forName(name);

		// 处理并得到注解DataSet的描述信息
		Annotation[] annotations = clazz.getAnnotations();
		for (Annotation annotation : annotations) {
			if (annotation.annotationType() == DataSet.class) {
				DataSet dataset = (DataSet) annotation;
				if(!dataset.idAttr().isEmpty())
					description.setIdAttr(dataset.idAttr());
				if(!dataset.css().isEmpty())
					description.setCss(dataset.css());
				if(!dataset.cssClass().isEmpty())
					description.setCssClass(dataset.cssClass());
				
				String[] names = dataset.name();
				Set<String> set = StringArrays.toHashSet(names);
				description.setNames(set);
			}
		}
		// 处理并得到注解DataField的描述信息
		List<DataFieldDescription> fieldsDescriptions = description.getDataFieldDescriptions();
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			DataFieldAnnotationHandler handler = new DataFieldAnnotationHandler(
					field, description.getNames());
			DataFieldDescription fieldDescription = handler.handle();
			if (fieldDescription == null) { // 不允许添加一个空属性进入fieldsDescriptions
				continue;
			}
			fieldsDescriptions.add(fieldDescription);
		}

		return description;
	}

	private static class StringArrays {
		// public static String[] trim(String[] strings){
		// Set<String> set = toHashSet(strings);
		// String[] result = set.toArray(new String[0]);
		// return result;
		// }

		public static Set<String> toHashSet(String[] strings) {
			Set<String> set = new HashSet<String>();
			for (String string : strings) {
				set.add(string);
			}
			return set;
		}
	}
}
